package com.wei.czz.framework.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.po.admin.deptRole.DeptRolePagePo;
import com.wei.czz.common.po.admin.userRole.UserRolePo;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.tool.PageQuery;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.admin.deptRole.DeptRoleFormVo;
import com.wei.czz.common.vo.admin.role.RoleFormVo;
import com.wei.czz.common.vo.admin.roleGroup.RoleGroupFormVo;
import com.wei.czz.framework.admin.dao.RoleDao;
import com.wei.czz.framework.admin.entity.RoleEntity;
import com.wei.czz.framework.admin.service.RoleService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-03-15 10:28:29
 * className: RoleServiceImpl 系统角色操作请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("roleService")
@AllArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {

    private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Override
    public void saveOrEdit(RoleEntity role) {
        Long roleId = role.getRoleId();
        if (Objects.isNull(roleId)) {

            int count = baseMapper.insert(role);
            log.info("添加角色完成。count={}", count);
        } else {
            int count = baseMapper.updateById(role);
            log.info("修改角色完成。count={}", count);
        }
    }

    @Transactional
    @Override
    public void batchSave(List<RoleEntity> roleList) {
        if (CollectionUtils.isEmpty(roleList)) {
            log.info("批量保存角色，传入的角色对象列表为空");
            return;
        }
        boolean bool = this.saveBatch(roleList);
        log.info("批量保存角色完成。bool={}", bool);
    }

    @Override
    public PageDto<RoleEntity> getPageList(RoleFormVo formVo) {

        // 构造mp分页对象
        Page<RoleEntity> page = PageQuery.initPage(formVo);

        LambdaQueryWrapper<RoleEntity> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(StringUtils.isNotBlank(formVo.getRoleKey()), RoleEntity::getRoleKey, formVo.getRoleKey())
                .eq(StringUtils.isNotBlank(formVo.getWord()), RoleEntity::getRoleName, formVo.getWord())
                .eq(Objects.nonNull(formVo.getBusinessType()), RoleEntity::getBusinessType, formVo.getBusinessType())
                .eq(Objects.nonNull(formVo.getStatus()), RoleEntity::getStatus, formVo.getStatus())
                .eq(RoleEntity::getDeleteStatus, formVo.getDeleteStatus());

        baseMapper.selectPage(page, roleLambdaQueryWrapper);
        log.info("分页查询角色完成。list.size={} totalNum={}", page.getRecords().size(), page.getTotal());
        return new PageDto<>(page);
    }

    @Override
    public PageDto<DeptRolePagePo> getDeptRolePageList(DeptRoleFormVo deptRoleFormVo) {
        deptRoleFormVo.setField("dr.`" + deptRoleFormVo.getField() + "`");
        // 构造mp分页对象
        Page<DeptRolePagePo> page = PageQuery.initPage(deptRoleFormVo);

        // 分页查询
        baseMapper.selectPageList(page, deptRoleFormVo);
        log.info("分页查询部门角色完成。totalNum={} size={}", page.getTotal(), page.getRecords().size());

        return new PageDto<>(page);
    }

    @Override
    public PageDto<RoleEntity> getRoleSpacePageList(RoleGroupFormVo roleGroupFormVo) {
        roleGroupFormVo.setField("r.`" + roleGroupFormVo.getField() + "`");
        // 构造mp分页对象
        Page<RoleEntity> page = PageQuery.initPage(roleGroupFormVo);

        // 分页查询
        baseMapper.selectRoleSpacePageList(page, roleGroupFormVo);
        log.info("分页查询角色授权组关联角色完成。list.size={} totalNum={}", page.getRecords().size(), page.getTotal());

        return new PageDto<>(page);
    }

    @Override
    public List<RoleEntity> getList() {
        LambdaQueryWrapper<RoleEntity> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(RoleEntity::getStatus, CommonEnum.ZERO.getValue())
                .eq(RoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查找
        List<RoleEntity> roleList = baseMapper.selectList(roleLambdaQueryWrapper);
        log.info("获取可用角色完成。size={}", roleList.size());
        roleList.sort(Comparator.comparing(RoleEntity::getSort));
        return roleList;
    }

    @Override
    public List<RoleEntity> getList(List<Long> roleIdList) {
        if (CollectionUtils.isEmpty(roleIdList)) {
            log.info("批量查询角色，传入角色主键列表为空");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<RoleEntity> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(RoleEntity::getRoleId, roleIdList)
                .eq(RoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<RoleEntity> roleList = baseMapper.selectList(roleLambdaQueryWrapper);
        log.info("批量查询角色完成。param.size={} list.size={}", roleIdList.size(), roleList.size());
        return roleList;
    }

    @Override
    public RoleEntity get(Long roleId) {
        // 查询
        RoleEntity role = baseMapper.selectById(roleId);
        if (Objects.isNull(role)) {
            log.info("角色不存在。roleId={}", roleId);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "角色不存在，请确认");
        }
        if (CommonEnum.ONE.getValue().equals(role.getDeleteStatus())) {
            log.info("角色已删除。roleId={}", roleId);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "角色不存在，请确认");
        }
        return role;
    }

    @Override
    public Integer getNextSort() {
        Integer maxSort = baseMapper.getMaxSort(CommonEnum.ZERO.getValue());
        if (maxSort == null) {
            maxSort = 0;
        }
        return maxSort + 1;
    }

    @Override
    public List<RoleEntity> findList(List<String> roleKeyList) {
        if (CollectionUtils.isEmpty(roleKeyList)) {
            log.info("获取角色，传入的角色键列表为空");
            return Collections.emptyList();
        }

        LambdaQueryWrapper<RoleEntity> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(RoleEntity::getRoleKey, roleKeyList)
                .eq(RoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<RoleEntity> roleList = baseMapper.selectList(roleLambdaQueryWrapper);
        log.info("查询角色完成。list.size={}", roleList.size());
        return roleList;
    }

    @Override
    public List<UserRolePo> findList(Long userId, Integer status) {
        List<UserRolePo> roleList = baseMapper.selectUserRoleList(userId, status, CommonEnum.ZERO.getValue());
        log.info("查询用户关联角色完成。userId={} size={}", userId, roleList.size());
        return roleList;
    }

    @Override
    public void delete(List<Long> roleIdList) {

        // 获取正在执行删除角色的用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<RoleEntity> roleLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        roleLambdaUpdateWrapper.set(RoleEntity::getDeleteStatus, CommonEnum.ONE.getValue())
                .set(RoleEntity::getUpdateTime, date)
                .set(RoleEntity::getUpdateUser, userPo.getUsername())
                .set(RoleEntity::getUpdateUserId, userPo.getUserId());
        // 批量 角色主键 字段
        roleLambdaUpdateWrapper.in(RoleEntity::getRoleId, roleIdList)
                .eq(RoleEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 操作数据库系统角色表，批量删除角色数据
        int count = baseMapper.update(null, roleLambdaUpdateWrapper);
        log.info("批量删除角色完成。count={}", count);
    }

}